import 'package:flutter/material.dart';

class TextFiledUtil {
  /// 填充数据
  /// [keepOffset] 保持原来的光标位置
  static setValue(TextEditingController controller, String value,
      {int? offset, bool keepOffset = false}) {
    var oldOffset = controller.selection.baseOffset;
    controller.text = value;
    var validOffset = offset ?? (keepOffset ? oldOffset : value.length);
    if (validOffset > value.length) {
      validOffset = value.length;
    }
    controller.selection = TextSelection.fromPosition(
        TextPosition(affinity: TextAffinity.downstream, offset: validOffset));
  }

  /// 设置光标位置
  static void setCursorSelection(
    TextEditingController controller, {
    required int start,
    int? end,
  }) {
    final textLength = controller.text.length;
    final safeStart = start.clamp(0, textLength);
    final safeEnd = (end ?? safeStart).clamp(0, textLength);

    controller.selection = TextSelection(
      baseOffset: safeStart,
      extentOffset: safeEnd,
    );
  }

  /// 清空当前焦点
  static clearFocus(BuildContext context) {
    FocusNode focusNode = FocusNode();
    FocusScope.of(context).requestFocus(focusNode);
  }
}
